import axios from "axios";
import router from "../router";
import Element from "element-ui"

axios.defaults.baseURL = "http://localhost:8081"

const request = axios.create({
    timeout: 5000,
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    }
})
//请求拦截
request.interceptors.request.use(config => {
    //获取请求头中的 token 信息
    config.headers['Authorization'] = localStorage.getItem("token")
    return config
})
//响应拦截
request.interceptors.response.use(response => {
    let res = response.data
    //状态码为200说明结果正确
    if(res.code === 200){
        return res
    }else{
        Element.Message.error(res.msg ? res.msg : '系统异常！', {duration: 3 * 1000})
        return Promise.reject(response.data.msg)
    }
}, error => {
    //当jwt过期后，登录信息报错就直接将其移除
    if(error.response.data.msg === "请进行登录"){
        localStorage.removeItem("token")
        location.reload()
    }
    //否则结果错误
    if(error.response.data) {
        error.message = error.response.data.msg
    }
    //权限不足转到登录页
    if(error.response.status === 401) {
        router.push("/login")
    }
    Element.Message.error(error.message, {duration: 3 * 1000})
    return Promise.reject(error)
})
export default request